package com.example.admin.mybledemo.ui;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import cn.com.heaton.blelibrary.ble.BleLog;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.example.admin.mybledemo.BleRssiDevice;
import com.example.admin.mybledemo.R;
import com.example.admin.mybledemo.OtaManager;
import com.example.admin.mybledemo.ota.OtaConfig;
import com.example.admin.mybledemo.ota.OtaConstants;
import com.example.admin.mybledemo.ota.OtaState;
import com.example.admin.mybledemo.ota.ProtocolVersion;

import java.io.InputStream;

import cn.com.heaton.blelibrary.ble.BleLog;
import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class OtaService extends Service implements OtaManager.OtaProgressListener {

    private static final String CHANNEL_ID = "OTA_CHANNEL";
    private static final int NOTIFICATION_ID = 1;

    private OtaManager otaManager;
    private OtaServiceCallback callback;

    public interface OtaServiceCallback {
        void onStateChanged(OtaState state);
        void onProgressChanged(int progress, int total);
        void onError(int errorCode, String errorMessage);
        void onSuccess();
    }

    public class OtaBinder extends Binder {
        public OtaService getService() {
            return OtaService.this;
        }
    }

    private final IBinder binder = new OtaBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
        otaManager = OtaManager.getInstance();
        otaManager.setProgressListener(this);
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "OTA Update",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("OTA升级进度");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private Notification createNotification(String contentText, int progress) {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("OTA升级")
            .setContentText(contentText)
            .setProgress(100, progress, false)
            .setOngoing(true)
            .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            stopSelf();
            return START_NOT_STICKY;
        }

        // 从Intent中获取设备属性并重新构造BleRssiDevice对象
        String deviceAddress = intent.getStringExtra("deviceAddress");
        String deviceName = intent.getStringExtra("deviceName");
        Uri fileUri = intent.getParcelableExtra("fileUri");
        String macCode = intent.getStringExtra("macCode");
        String creditCode = intent.getStringExtra("creditCode");

        if (deviceAddress == null || fileUri == null) {
            Toast.makeText(this, "OTA Service: Missing device address or file URI", Toast.LENGTH_SHORT).show();
            stopSelf();
            return START_NOT_STICKY;
        }

        // 检查文件读取权限
        if (!checkFileReadPermission()) {
            BleLog.d("OtaService", "文件读取权限不足");
            Toast.makeText(this, "文件读取权限不足，无法进行OTA升级", Toast.LENGTH_LONG).show();
            stopSelf();
            return START_NOT_STICKY;
        }

        // 重新构造BleRssiDevice对象
        BleRssiDevice device = new BleRssiDevice(deviceAddress, deviceName);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 需要指定前台服务类型
            startForeground(NOTIFICATION_ID, createNotification("准备升级...", 0), ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
        } else {
            startForeground(NOTIFICATION_ID, createNotification("准备升级...", 0));
        }

        try {
            InputStream firmwareStream = getContentResolver().openInputStream(fileUri);
            if (firmwareStream == null) {
          
                BleLog.d("OtaService", "无法打开OTA文件");
                Toast.makeText(this, "无法打开OTA文件", Toast.LENGTH_SHORT).show();
                stopSelf();
                return START_NOT_STICKY;
            }
            
            // 使用用户输入的MAC码进行凭证验证
            String actualMacAddress = device.getBleAddress(); // 设备实际MAC地址
            BleLog.d("OtaService", "设备实际MAC地址: " + actualMacAddress);
            BleLog.d("OtaService", "用户输入MAC码: " + macCode);
            BleLog.d("OtaService", "用户输入授权码: " + creditCode);
            BleLog.d("OtaService", "使用用户输入的MAC码进行凭证验证");
            
            // 禁用版本检查，只进行ROM版本比较
            OtaConfig config = OtaConfig.createDefault();
            config.enableVersionCheck = false;
            // 重要：保持重试次数为10，与Flutter端保持一致
            config.maxRetryCount = OtaConstants.MAX_RETRY_COUNT;
            config.connectTimeout = OtaConstants.CONNECT_TIMEOUT;
            otaManager.setConfig(config);
            BleLog.d("OtaService", "已禁用软件版本检查，只进行ROM版本比较");
            BleLog.d("OtaService", "重试次数: " + config.maxRetryCount + ", 连接超时: " + config.connectTimeout + "ms");
            
            otaManager.startOta(device, firmwareStream, creditCode, macCode);
        } catch (Exception e) {
            BleLog.d("OtaService", "OTA文件打开失败: " + e.getMessage());
            Toast.makeText(this, "OTA文件打开失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            stopSelf();
        }

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public void setCallback(OtaServiceCallback callback) {
        this.callback = callback;
    }
    
    public void stopOta() {
        BleLog.d("OtaService", "停止OTA升级");
        if (otaManager != null) {
            otaManager.stopOta();
        }
        updateNotification("升级已取消", 0);
        stopSelf();
    }

    @Override
    public void onStateChanged(OtaState state) {
        if (callback != null) {
            callback.onStateChanged(state);
        }
        updateNotification("状态: " + state.getDescription(), 0);
    }

    @Override
    public void onProgressChanged(int progress, int total) {
        if (callback != null) {
            callback.onProgressChanged(progress, total);
        }
        int progressPercent = (int) ((double) progress / total * 100);
        updateNotification("升级中... " + progressPercent + "%", progressPercent);
    }

    @Override
    public void onError(int errorCode, String errorMessage) {
        if (callback != null) {
            callback.onError(errorCode, errorMessage);
        }
        updateNotification("升级失败: " + errorMessage, 0);
        stopSelf();
    }

    @Override
    public void onSuccess() {
        if (callback != null) {
            callback.onSuccess();
        }
        updateNotification("升级完成", 100);
        stopSelf();
    }

    @Override
    public void onLog(String message) {
        // Log messages are handled by callback
    }

    @Override
    public void onVersionInfo(String deviceVersion, String romVersion, String targetVersion) {
        // Version info is handled by callback
    }

    @Override
    public void onProtocolDetected(ProtocolVersion version) {
        // Protocol detection is handled by callback
    }

    private void updateNotification(String contentText, int progress) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, createNotification(contentText, progress));
    }

    /**
     * 检查文件读取权限
     */
    private boolean checkFileReadPermission() {
        try {
            // 检查文件读取权限（Android 6.0+）
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                int permission = checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE);
                if (permission != android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    BleLog.d("OtaService", "READ_EXTERNAL_STORAGE权限未授予");
                    return false;
                }
            }
            
            // 检查文件写入权限（Android 11以下）
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.R) {
                int permission = checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (permission != android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    BleLog.d("OtaService", "WRITE_EXTERNAL_STORAGE权限未授予");
                    return false;
                }
            }
            
            BleLog.d("OtaService", "文件权限检查通过");
            return true;
        } catch (Exception e) {
            BleLog.e("OtaService", "权限检查失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (otaManager != null) {
            otaManager.release();
        }
    }
} 